<?php

/**
 * This file holds the library functions for user.
 * 
 * @package User_library
 */


require_once("lib/db.lib.php");
 
/**
 * Create a new user account.
 * 
 * @param	string	$username	Username of the new user.
 * @param	string	$md5pw		Password of the new user (should be md5-ed).
 * @param	bool	$no_escape	Indicate whether to escape the variables or not.
 * 
 * @return	int|FALSE	<b>User ID</b> on success, <b>FALSE</b> on failure.
 */
function user_add_new_user($username, $md5pw, $no_escape = FALSE){
	
	db_connect();
	
	
	if(!$no_escape){
		$username = mysql_real_escape_string($username);
		$md5pw = mysql_real_escape_string($md5pw);
	}
	
	$sql = "INSERT INTO `user_info` (`user_name`, `user_password`) VALUES (\"$username\", \"$md5pw\");";
	
	
	mysql_query("LOCK TABLES user_info WRITE;");
	
	$result = mysql_query($sql);
		
	$user_id = mysql_insert_id();	
	
	mysql_query("UNLOCK TABLES;");
	
	
	//return
	if($result){
		return $user_id;
	}
		
	return FALSE;
}

 /**
 * Check whether a user name exists.
 * 
 * @param	string	$username	Username in question.
 * @param	bool	$no_escape	Indicate whether to escape the variables or not.
 * 
 * @return	bool	<b>TRUE</b> if exists, <b>FALSE</b> if not.
 */
function user_is_exists($username, $no_escape = FALSE){
	
	db_connect();
	
	
	if(!$no_escape){
		$username = mysql_real_escape_string($username);
	}
	
	$sql = "SELECT `user_id` FROM `user_info` WHERE `user_name` = \"$username\";";
	
	$result = mysql_query($sql);
		
	
	//return
	if(mysql_num_rows($result) > 0){
		return TRUE;
	}
		
	return FALSE;	
}

 /**
 * Check if the password of a user is correct.
 * 
 * @param	string	$username	Username of the user.
 * @param	string	$md5pw		Password of the user (should be md5-ed).
 * @param	bool	$no_escape	Indicate whether to escape the variables or not.
 * 
 * @return	bool	<b>TRUE</b> if correct, <b>FALSE</b> if not.
 */
function user_check_password($username, $md5pw, $no_escape = FALSE){

	db_connect();
	
	
	if(!$no_escape){
		$username = mysql_real_escape_string($username);
		$md5pw = mysql_real_escape_string($md5pw);
	}
	
	$sql = "SELECT `user_id` FROM `user_info` WHERE `user_name` = \"$username\" AND BINARY `user_password` = \"$md5pw\";";
	
	$result = mysql_query($sql);
		
	
	//return
	if(mysql_num_rows($result) > 0){
		return TRUE;
	}
		
	return FALSE;	
}


/**
 * Get the points of a user
 * 
 * @param	int		$game_id		Game ID.
 * @param	int		$user_id		User ID.
 * 
 * @return	int|FALSE	<b>Points</b> of user, <b>FALSE</b> if failed.
 */
function user_get_points($user_id){

	db_connect();
	
	$sql = "SELECT `user_points` FROM `user_info` WHERE `user_id` = \"$user_id\";";
	
	$result = mysql_query($sql);
	
	if($row = mysql_fetch_assoc($result)){
		return (int) $row['user_points'];
	}
		
	return FALSE;
}


